package org.example.repeater.server;

import com.github.benmanes.caffeine.cache.Cache;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.example.repeater.handler.core.Delimiter;
import org.example.repeater.handler.core.DelimiterBasedFrameDecoder;
import org.example.repeater.handler.deviceHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class deviceServer {
    private static final Logger log = LoggerFactory.getLogger(deviceServer.class);
    private static  ServerBootstrap serverBootstrap ;
    private static EventLoopGroup bossGroup;
    private static EventLoopGroup workerGroup ;
    public static void start(int inputPort, Cache<String, Object> caffeineCache) {
            serverBootstrap = new ServerBootstrap();
            bossGroup = new NioEventLoopGroup();
            workerGroup = new NioEventLoopGroup(new DefaultThreadFactory("Device", true));
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(
                               //标识位[2] + 消息头[21] + 消息体[1023 * 2(转义预留)]  + 校验码[1] + 标识位[2]
                               new DelimiterBasedFrameDecoder(
                                       2 + 21 + 1023 * 2 + 1 + 2,new Delimiter(new byte[]{0x7e}, false)),
                              new deviceHandler(caffeineCache)
                            );

                        }
                    });

        try {
            ChannelFuture f = serverBootstrap.bind("127.0.0.1", inputPort).sync();
            log.info("服务启动成功，终端连接端口：{}", inputPort);
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("服务启动失败,原因如下:{}", e.getMessage());
        }
    }
    public static void close() {
        try {
            bossGroup.shutdownGracefully().sync();
            workerGroup.shutdownGracefully().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }



}
